<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
</body>
<script>
    function fn() {
        setTimeout(function () {
            //创建随机方块
            var square = document.createElement("div");
            square.style.width = 15 + 'px'
            square.style.height = 15 + 'px'
            square.style.position = "absolute";
            //随机位置
            square.style.left = Math.round(Math.random() * document.documentElement.clientWidth) - 15 + "px";
            square.style.top = Math.round(Math.random() * document.documentElement.clientHeight) + 15 + "px";
            // var topmax = document.documentElement.clientHeight-200 + 'px'
            // if(square.style.top > topmax) square.style.top = topmax
            //方块随机颜色
            var arr = ['red', 'gold', 'green', 'skyblue', 'red']
            square.style.backgroundColor = arr[Math.floor(Math.random() * 4)]
            document.body.append(square)
            //点击随机方块消失
            square.onmousedown = function (e) {
                var e = e || window.event;
                this.style.display = "none"
            }
            //离开页面
            document.onkeypress =function(e){
                var e = e || window.event;
                var keyCode = e.keyCode;
                console.log(e.keyCode);
                if(keyCode == 122){
                    alert("是要离开我了吗？")
                    alert("还会再见吗？")
                    var res = confirm("再见的时候你要幸福，燕子")
                    if (res) {
                        window.close()
                    }
                }
            }
            fn()
        }, 500)
    }
    fn()
</script>

</html>